import 'package:after_sale_plugin/package_event.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/language/language_util.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import 'package:after_sale_plugin/constant.dart';
import 'package:after_sale_plugin/pages/models/order_model.dart';
import 'state.dart';

class ProblemResolutionController extends LxBaseScrollOpacityController {
  // 状态
  ProblemResolutionState state = ProblemResolutionState();

  @override
  onInit() async {
    super.onInit();

    // 页面数据
    if (Get.arguments != null) {
      state.id = Get.arguments;
    }

    // 监听 资源文件
    state.assets.listen((p0) {
      state.assetUploadCompleted.value =
          p0.every((element) => element.src.isNotEmpty || element.isAdd);
    });
  }

  // 重新提交 资源文件
  submit() {
    if (state.resolutionContent.value.isEmpty) {
      return;
    }
    bool isSubmited = false;
    sub() {
      if (isSubmited) return;
      ReportOrderInfo reportOrderInfo = ReportOrderInfo.fromMap({});
      reportOrderInfo.id = state.id;
      reportOrderInfo.resolutionResult.value.attachment.value =
          state.assets.map((element) => element.src).toList();
      reportOrderInfo.resolutionResult.value.comment.value =
          state.resolutionContent.value;
      PackageEvent.orderUnsolved((p0) {
        if (p0) {
          PackageEventStream().fire(REFRESH_ORDER_LIST);
          PackageEvent.showConfirmAlert(
            AppLanguageUtil.to.submitOrderSuccessPrompts,
            confirmTitle: AppLanguageUtil.to.titleOK,
            isShowCancel: false,
            confirmCallBack: (p0) {
              Get.back(result: state.id);
            },
          );
        }
      }, param: reportOrderInfo.toJson());
      isSubmited = true;
    }

    if (state.assetUploadCompleted.value) {
      sub();
    } else {
      PackageEvent.showLoading();
      state.assetUploadCompleted.listen((p0) {
        if (p0) sub();
      });
      // 5秒后，无论是否上传完成，都进行提交
      Future.delayed(const Duration(seconds: 5), () {
        sub();
      });
    }
  }
}
